package wiki.zimo.servlet.reception;

import org.apache.commons.beanutils.BeanUtils;
import wiki.zimo.constant.Constant;
import wiki.zimo.dao.Dao;
import wiki.zimo.dao.UserDao;
import wiki.zimo.domain.User;
import wiki.zimo.servlet.BaseServlet;
import wiki.zimo.utils.MailUtils;
import wiki.zimo.utils.UUIDUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @version v1.0
 * @auther: 子墨
 * @datetime: 2018/10/31 9:33
 * @description: 处理用户（登录，注册，激活店主）操作的Servlet
 */
@WebServlet(value = "/user")
public class UserServlet extends BaseServlet {

    // 数据库操作对象
    private Dao dao = new UserDao();

    /**
     * @auther: 子墨
     * @date: 2018/10/31 9:42
     * @describe: 跳转到用户注册页
     * @param: [request, response]
     * @return: java.lang.String
     * @version v1.0
     */
    public String registerPage(HttpServletRequest request, HttpServletResponse response) {
        return Constant.URL_USER_REGISTER;
    }

    /**
     * @auther: 子墨
     * @date: 2018/10/31 11:01
     * @describe: 跳转到用户登录页
     * @param: [request, response]
     * @return: java.lang.String
     * @version v1.0
     */
    public String loginPage(HttpServletRequest request, HttpServletResponse response) {
        return Constant.URL_USER_LOGIN;
    }

    /**
     * @auther: 子墨
     * @date: 2018/10/31 22:36
     * @describe: 用户注册接口
     * @param: [request, response]
     * @return: java.lang.String
     * @version v1.0
     */
    public String register(HttpServletRequest request, HttpServletResponse response) {

        try {
            // 检查手机号是否重复
            String tel = request.getParameter("telephone");
            User user = (User) dao.findOneByParams(new String[]{tel});
            if (user != null) {
                request.setAttribute(Constant.MSG, Constant.MSG_USER_REGISTER_FAIL);
                return Constant.URL_USER_REGISTER;
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute(Constant.MSG, Constant.MSG_USER_REGISTER_ERROR);
            return Constant.URL_USER_REGISTER;
        }

        User user = new User();
        try {
            // 利用BeanUtils获取请求参数封装为对象
            BeanUtils.populate(user, request.getParameterMap());

            // 自动生成用户的id，激活码
            user.setUid(UUIDUtils.getRandomId());
            user.setCode(UUIDUtils.getRandomCode());
            // 默认用户注册成功后未激活
            user.setState(Constant.USER_IS_NOT_ACTIVE);
            // 注册的用户都不是管理员
            user.setIsadmin(Constant.NOT_ADMIN);

            dao.insert(user);

            request.getSession().setAttribute(Constant.MSG, Constant.MSG_USER_REGISTER_SUCCESS);
            // 注册成功，发送邮件，跳转到登录页
            // 发送激活的邮件
            String emailTitle = "激活账户";
            String emailMsg = "恭喜<em>" + user.getUsername() + "</em>成为子墨商城的首批注册用户，请点击<a href='" + Constant.URL + "/user?method=active&uid=" + user.getUid() + "'" + ">此</a>激活你的账户。<br><img src='" + Constant.URL + "/asserts/img/logo.png' alt='子墨商城'>";
            MailUtils.sendQQMail(user.getEmail(), emailTitle, emailMsg);
            return Constant.REDIRECT + Constant.URL_USER_LOGIN;
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute(Constant.MSG, Constant.MSG_USER_REGISTER_ERROR);
            return Constant.URL_USER_REGISTER;
        }
    }

    /**
     * @auther: 子墨
     * @date: 2018/10/31 16:31
     * @describe: 用户登录接口
     * @param: [request, response]
     * @return: java.lang.String
     * @version v1.0
     */
    public String login(HttpServletRequest request, HttpServletResponse response) {

        HttpSession session = request.getSession();
        // 获取后台的验证码
        String verifyCode = (String) session.getAttribute(Constant.VERIFY_CODE);
        // 获取用户提交的验证码
        String code = request.getParameter("code");

        if (!verifyCode.equalsIgnoreCase(code)) {
            // 验证码不正确
            request.setAttribute(Constant.MSG, Constant.MSG_VERIFY_CODE_ERROR);
            return Constant.URL_USER_LOGIN;
        }

        String tel = request.getParameter("tel");
        String pwd = request.getParameter("pwd");

        try {
            User user = (User) dao.findOneByParams(new String[]{tel, pwd});
            if (user == null) {
                // 用户未找到
                request.setAttribute(Constant.MSG, Constant.MSG_TEL_PWD_NOT_MATCH);
                return Constant.URL_USER_LOGIN;
            }

            if (Constant.USER_IS_ACTIVE_YET != user.getState()) {
                // 用户未激活账户
                request.setAttribute(Constant.MSG, Constant.MSG_USER_IS_NOT_ACTIVE);
                return Constant.URL_USER_LOGIN;
            }

            // 登录成功，保存用户信息到session，跳转到首页
            session.setAttribute(Constant.USER_LOG_ON, user);
            // 登录成功后提示信息已经没用了，移除
            session.removeAttribute(Constant.MSG);

            return Constant.REDIRECT + "/";
        } catch (Exception e) {
            e.printStackTrace();
            // 数据查询异常
            request.setAttribute(Constant.MSG, Constant.MSG_EXCEPTION);
            return Constant.URL_USER_LOGIN;
        }
    }

    /**
     * @auther: 子墨
     * @date: 2018/11/4 19:21
     * @describe: 退出登录接口
     * @param: [request, response]
     * @return: java.lang.String
     * @version v1.0
     */
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        session.removeAttribute(Constant.USER_LOG_ON);
        session.removeAttribute(Constant.CART);
        return Constant.URL_USER_LOGIN;
    }

    /**
     * @auther: 子墨
     * @date: 2018/10/31 23:12
     * @describe: 用户激活接口
     * @param: [request, response]
     * @return: java.lang.String
     * @version v1.0
     */
    public String active(HttpServletRequest request, HttpServletResponse response) {

        // 获取到请求激活的用户id
        String uid = request.getParameter("uid");
        User user = null;

        try {
            user = (User) dao.findOneById(uid);
            if (user == null) {
                // 没找到用户
                request.setAttribute(Constant.MSG, Constant.MSG_USER_ACTIVE_ERROR);
                return Constant.URL_USER_REGISTER;
            }
            user.setState(Constant.USER_IS_ACTIVE_YET);
            dao.update(user);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute(Constant.MSG, Constant.MSG_USER_ACTIVE_ERROR);
            return Constant.URL_USER_REGISTER;
        }
        // 激活成功
        request.setAttribute(Constant.MSG, Constant.MSG_USER_ACTIVE_SUCCE);
        return Constant.URL_USER_LOGIN;
    }
}
